﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.TestCode;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.Test.Dtos.Write;
using Newtonsoft.Json;

namespace ERPWinFormWork.Test
{
    public partial class UpdateOutInspection : Form
    {
        private ApiClient _apiClient;
        private int _inspectionId;
        private Action _refreshCallback;
        private Goods_InspectionDtos _inspectionData;
        private int? _selectedSaleId;
        private int? _selectedProductId;

        public UpdateOutInspection(int inspectionId, Action refreshCallback)
        {
            InitializeComponent();
            _inspectionId = inspectionId;
            _refreshCallback = refreshCallback;
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            // 初始化表格和事件
            InitializeGridAndEvents();

            // 加载检验数据
            LoadInspectionData();
        }

        /// <summary>
        /// 初始化表格和事件
        /// </summary>
        private void InitializeGridAndEvents()
        {
            // 配置检测项目表格
            ConfigureTestingItemsGrid();

            // 绑定事件
            if (dgvtesting_ItemsId != null)
            {
                dgvtesting_ItemsId.CellContentClick += dgvtesting_ItemsId_CellContentClick;
                dgvtesting_ItemsId.DataBindingComplete += Dgvtesting_ItemsId_DataBindingComplete;
                dgvtesting_ItemsId.CellValueChanged += dgvtesting_ItemsId_CellValueChanged;
            }

            // 添加数量变化事件监听器
            AddCalculationEventListeners();

            // 设置缺陷率文本框为只读
            SetDefectRateTextBoxesReadOnly();
        }

        /// <summary>
        /// 配置检测项目表格
        /// </summary>
        private void ConfigureTestingItemsGrid()
        {
            if (dgvtesting_ItemsId == null) return;

            var grid = dgvtesting_ItemsId;
            grid.AllowUserToAddRows = false;

            // 添加缺陷数量列
            if (!grid.Columns.Contains("colFatalCount"))
            {
                var colFatal = new DataGridViewTextBoxColumn
                {
                    Name = "colFatalCount",
                    HeaderText = "致命缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colFatal);
            }

            if (!grid.Columns.Contains("colSeriousCount"))
            {
                var colSerious = new DataGridViewTextBoxColumn
                {
                    Name = "colSeriousCount",
                    HeaderText = "严重缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colSerious);
            }

            if (!grid.Columns.Contains("colMinorCount"))
            {
                var colMinor = new DataGridViewTextBoxColumn
                {
                    Name = "colMinorCount",
                    HeaderText = "轻微缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colMinor);
            }

            // 添加操作列
            if (!grid.Columns.Contains("colDefect"))
            {
                var defectCol = new DataGridViewButtonColumn
                {
                    Name = "colDefect",
                    HeaderText = "操作",
                    Text = "缺陷填报",
                    UseColumnTextForButtonValue = true,
                    Width = 90
                };
                grid.Columns.Add(defectCol);
            }

            if (!grid.Columns.Contains("colDelete"))
            {
                var deleteCol = new DataGridViewButtonColumn
                {
                    Name = "colDelete",
                    HeaderText = string.Empty,
                    Text = "删除",
                    UseColumnTextForButtonValue = true,
                    Width = 70
                };
                grid.Columns.Add(deleteCol);
            }
        }

        /// <summary>
        /// 添加数量变化事件监听器
        /// </summary>
        private void AddCalculationEventListeners()
        {
            if (textinspection_Count != null)
            {
                textinspection_Count.TextChanged += (s, e) => CalculateQuantitiesAndRates();
            }

            if (textqualified_Count != null)
            {
                textqualified_Count.TextChanged += (s, e) => CalculateQuantitiesAndRates();
            }
        }

        /// <summary>
        /// 设置缺陷率文本框为只读
        /// </summary>
        private void SetDefectRateTextBoxesReadOnly()
        {
            if (textfatal_Defect_Rate != null) textfatal_Defect_Rate.ReadOnly = true;
            if (textserious_Defect_Rate != null) textserious_Defect_Rate.ReadOnly = true;
            if (textminor_Defect_Rate != null) textminor_Defect_Rate.ReadOnly = true;
            if (textnoQualified_Count != null) textnoQualified_Count.ReadOnly = true;
            if (textdetection_Result != null) textdetection_Result.ReadOnly = true;
        }

        /// <summary>
        /// 自动计算不合格数量和缺陷率
        /// </summary>
        private void CalculateQuantitiesAndRates()
        {
            try
            {
                // 检查是否有检测项目
                if (dgvtesting_ItemsId == null || dgvtesting_ItemsId.Rows.Count == 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 检查控件是否存在
                if (textinspection_Count == null || textqualified_Count == null)
                {
                    return;
                }

                // 获取文本值并验证
                string inspectionCountText = textinspection_Count.Text?.Trim();
                string qualifiedCountText = textqualified_Count.Text?.Trim();

                if (string.IsNullOrEmpty(inspectionCountText) || string.IsNullOrEmpty(qualifiedCountText))
                {
                    ClearCalculationResults();
                    return;
                }

                // 解析检测数量和合格数量
                if (!int.TryParse(inspectionCountText, out int inspectionCount) || inspectionCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                if (!int.TryParse(qualifiedCountText, out int qualifiedCount) || qualifiedCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 验证合格数量不能超过检测数量
                if (qualifiedCount > inspectionCount)
                {
                    ClearCalculationResults();
                    return;
                }

                // 验证检测数量必须大于0
                if (inspectionCount <= 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 计算不合格数量
                int noQualifiedCount = Math.Max(0, inspectionCount - qualifiedCount);

                // 更新不合格数量文本框
                if (textnoQualified_Count != null)
                {
                    textnoQualified_Count.Text = noQualifiedCount.ToString();
                }

                // 计算各类缺陷数量总和
                int totalFatal = 0, totalSerious = 0, totalMinor = 0;

                if (dgvtesting_ItemsId != null && dgvtesting_ItemsId.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                    {
                        // 获取致命缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colFatalCount"].Value.ToString(), out int fatal) && fatal >= 0)
                            {
                                totalFatal += fatal;
                            }
                        }

                        // 获取严重缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colSeriousCount"].Value.ToString(), out int serious) && serious >= 0)
                            {
                                totalSerious += serious;
                            }
                        }

                        // 获取轻微缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colMinorCount"].Value.ToString(), out int minor) && minor >= 0)
                            {
                                totalMinor += minor;
                            }
                        }
                    }
                }

                // 计算缺陷率（百分比）
                double fatalRate = inspectionCount > 0 ? (double)totalFatal / inspectionCount * 100 : 0;
                double seriousRate = inspectionCount > 0 ? (double)totalSerious / inspectionCount * 100 : 0;
                double minorRate = inspectionCount > 0 ? (double)totalMinor / inspectionCount * 100 : 0;

                // 更新缺陷率文本框
                if (textfatal_Defect_Rate != null)
                {
                    textfatal_Defect_Rate.Text = fatalRate.ToString("F2");
                }
                if (textserious_Defect_Rate != null)
                {
                    textserious_Defect_Rate.Text = seriousRate.ToString("F2");
                }
                if (textminor_Defect_Rate != null)
                {
                    textminor_Defect_Rate.Text = minorRate.ToString("F2");
                }

                // 根据缺陷率判断检测结果
                string detectionResult = DetermineDetectionResult(fatalRate, seriousRate, minorRate);
                if (textdetection_Result != null)
                {
                    textdetection_Result.Text = detectionResult;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"计算过程中出现异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空计算结果
        /// </summary>
        private void ClearCalculationResults()
        {
            if (textnoQualified_Count != null) textnoQualified_Count.Text = "0";
            if (textfatal_Defect_Rate != null) textfatal_Defect_Rate.Text = "0.00";
            if (textserious_Defect_Rate != null) textserious_Defect_Rate.Text = "0.00";
            if (textminor_Defect_Rate != null) textminor_Defect_Rate.Text = "0.00";
            if (textdetection_Result != null) textdetection_Result.Text = "合格";
        }

        /// <summary>
        /// 清除所有缺陷数量
        /// </summary>
        private void ClearAllDefectCounts()
        {
            if (dgvtesting_ItemsId != null && dgvtesting_ItemsId.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                {
                    if (dgvtesting_ItemsId.Columns.Contains("colFatalCount"))
                    {
                        row.Cells["colFatalCount"].Value = 0;
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount"))
                    {
                        row.Cells["colSeriousCount"].Value = 0;
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colMinorCount"))
                    {
                        row.Cells["colMinorCount"].Value = 0;
                    }
                }
            }
        }

        /// <summary>
        /// 根据缺陷率判断检测结果
        /// </summary>
        private string DetermineDetectionResult(double fatalRate, double seriousRate, double minorRate)
        {
            if (fatalRate > 5.0 || seriousRate > 7.0 || minorRate > 10.0)
            {
                return "不合格";
            }
            else
            {
                return "合格";
            }
        }

        /// <summary>
        /// 加载检验数据
        /// </summary>
        private async void LoadInspectionData()
        {
            try
            {
                // 添加调试信息
                Console.WriteLine($"正在加载检验数据，检验ID: {_inspectionId}");

                // 根据检验ID获取检验数据
                var response = await _apiClient.GetAsync<TestApiResult<List<Goods_InspectionDtos>>>(
                    endpoint: $"api/Read/FindGoods_MaterialById?id={_inspectionId}",
                    parameters: null
                );

                if (response != null && response.code == 200 && response.data != null && response.data.Count > 0)
                {
                    _inspectionData = response.data[0];
                    FillFormData();
                }
                else
                {
                    MessageBox.Show("获取检验数据失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        /// <summary>
        /// 填充表单数据
        /// </summary>
        private void FillFormData()
        {
            if (_inspectionData == null) return;

            try
            {
                // 填充基本信息
                if (textinspectionNode != null)
                    textinspectionNode.Text = _inspectionData.InspectionNode ?? string.Empty;

                if (textinspectionName != null)
                    textinspectionName.Text = _inspectionData.InspectionName ?? string.Empty;

                if (textaddbatch != null)
                    textaddbatch.Text = _inspectionData.Batch ?? string.Empty;

                if (textproductcode != null)
                    textproductcode.Text = _inspectionData.Product_Number ?? string.Empty;

                if (textproductname != null)
                    textproductname.Text = _inspectionData.Product_Name ?? string.Empty;

                if (textproductxh != null)
                    textproductxh.Text = _inspectionData.Specification ?? string.Empty;

                if (textproductunit != null)
                    textproductunit.Text = _inspectionData.Unit ?? string.Empty;

                // 填充备注信息
                if (textnotes != null)
                    textnotes.Text = _inspectionData.Notes ?? string.Empty;

                // 填充日期信息
                if (datetimeshipment_Date != null)
                {
                    // 直接使用DateTime类型，不需要字符串转换
                    datetimeshipment_Date.text = _inspectionData.Shipment_Date.ToString("yyyy-MM-dd");
                }

                if (datetimeinspection_Date != null)
                {
                    // 直接使用DateTime类型，不需要字符串转换
                    datetimeinspection_Date.text = _inspectionData.Inspection_Date.ToString("yyyy-MM-dd");
                }

                // 填充下拉框选择
                if (cboadddepartment_Id != null && _inspectionData.Department_Id.HasValue)
                {
                    // 这里需要先加载部门数据，然后设置选中值
                    LoadDepartmentData();
                }

                // 注意：这个窗体没有产品下拉框，只有产品相关的文本框
                // 如果需要产品选择功能，需要添加对应的控件

                if (textdetection_Result != null && !string.IsNullOrEmpty(_inspectionData.Detection_Result))
                {
                    textdetection_Result.Text = _inspectionData.Detection_Result;
                }

                // 填充检验统计信息
                if (textminor_Defect_Rate != null)
                    textminor_Defect_Rate.Text = _inspectionData.Minor_Defect_Rate?.ToString() ?? string.Empty;

                if (textserious_Defect_Rate != null)
                    textserious_Defect_Rate.Text = _inspectionData.Serious_Defect_Rate?.ToString() ?? string.Empty;

                if (textfatal_Defect_Rate != null)
                    textfatal_Defect_Rate.Text = _inspectionData.Fatal_Defect_Rate?.ToString() ?? string.Empty;

                if (textnoQualified_Count != null)
                    textnoQualified_Count.Text = _inspectionData.NoQualified_Count?.ToString() ?? string.Empty;

                if (textqualified_Count != null)
                    textqualified_Count.Text = _inspectionData.Qualified_Count?.ToString() ?? string.Empty;

                if (textinspection_Count != null)
                    textinspection_Count.Text = _inspectionData.Inspection_Count?.ToString() ?? string.Empty;

                // 设置产品相关字段
                _selectedSaleId = _inspectionData.Sale_Id;
                _selectedProductId = _inspectionData.ProductId;

                // 添加调试信息
                Console.WriteLine($"设置销售ID: {_selectedSaleId}, 产品ID: {_selectedProductId}");

                // 加载检测项目数据
                LoadTestingItemsData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"填充表单数据时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载检测项目数据
        /// </summary>
        private async void LoadTestingItemsData()
        {
            try
            {
                if (_inspectionData?.InspectionNode == null) return;

                // 添加调试信息
                Console.WriteLine($"正在加载检测项目数据，检验编号: {_inspectionData.InspectionNode}");

                // 根据检验编号查询检测项目
                var response = await _apiClient.GetAsync<TestApiResult<List<Testing_ItemsDtos>>>(
                    endpoint: $"api/Read/FindTesting_ItemsByItemId?inspectionNode={_inspectionData.InspectionNode}",
                    parameters: null
                );

                if (response != null && response.code == 200 && response.data != null)
                {
                    // 绑定检测项目数据到表格
                    dgvtesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(response.data);

                    // 加载缺陷数量数据并反填
                    await LoadDefectCountsAndFillBack();
                }
                else
                {
                    // 如果没有数据，设置为空列表
                    dgvtesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(new List<Testing_ItemsDtos>());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载检测项目数据异常：{ex.Message}");
                // 异常时设置为空列表
                dgvtesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(new List<Testing_ItemsDtos>());
            }
        }

        /// <summary>
        /// 加载缺陷数量数据并反填到表格
        /// </summary>
        private async Task LoadDefectCountsAndFillBack()
        {
            try
            {
                if (_inspectionData?.InspectionNode == null || dgvtesting_ItemsId == null) return;

                // 根据检验编号查询缺陷数量（API返回的是数组）
                var defectResponse = await _apiClient.GetAsync<TestApiResult<List<DefectCountDtos>>>(
                    endpoint: $"api/Read/FindCommon_DefectsCountByCode?inspectionNode={_inspectionData.InspectionNode}",
                    parameters: null
                );

                if (defectResponse != null && defectResponse.code == 200 && defectResponse.data != null)
                {
                    var defectDataList = defectResponse.data;

                    // 遍历表格中的检测项目，根据检测项Id匹配并反填缺陷数量
                    foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                    {
                        if (row.DataBoundItem is Testing_ItemsDtos testingItem)
                        {
                            // 在缺陷数据列表中查找匹配的检测项
                            var matchingDefectData = defectDataList.FirstOrDefault(d => d.testing_ItemsId == testingItem.Id);

                            if (matchingDefectData != null)
                            {
                                // 反填缺陷数量到对应的列
                                if (dgvtesting_ItemsId.Columns.Contains("colFatalCount"))
                                {
                                    row.Cells["colFatalCount"].Value = matchingDefectData.fatal_DefectCount;
                                }
                                if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount"))
                                {
                                    row.Cells["colSeriousCount"].Value = matchingDefectData.serious_DefectCount;
                                }
                                if (dgvtesting_ItemsId.Columns.Contains("colMinorCount"))
                                {
                                    row.Cells["colMinorCount"].Value = matchingDefectData.minor_DefectCount;
                                }

                                Console.WriteLine($"已为检测项 {testingItem.Items_Name} (ID: {testingItem.Id}) 反填缺陷数量");
                            }
                            else
                            {
                                Console.WriteLine($"未找到检测项 {testingItem.Items_Name} (ID: {testingItem.Id}) 的缺陷数据");
                            }
                        }
                    }

                    // 反填完成后触发重新计算
                    CalculateQuantitiesAndRates();
                }
                else
                {
                    Console.WriteLine($"获取缺陷数量数据失败: {defectResponse?.msg ?? "未知错误"}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载缺陷数量数据异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 加载部门数据
        /// </summary>
        private async void LoadDepartmentData()
        {
            try
            {
                var response = await _apiClient.GetAsync<TestApiResult<List<DepartmentDtos>>>(
                    endpoint: "api/Read/GetDepartment");

                if (response != null && response.code == 200 && cboadddepartment_Id != null)
                {
                    cboadddepartment_Id.Items.Clear();
                    cboadddepartment_Id.DisplayMember = "departmentName";
                    cboadddepartment_Id.ValueMember = "id";
                    cboadddepartment_Id.DataSource = response.data;

                    // 设置选中值
                    if (_inspectionData.Department_Id.HasValue)
                    {
                        cboadddepartment_Id.SelectedValue = _inspectionData.Department_Id.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载部门数据异常：{ex.Message}");
            }
        }



        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private async void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 至少需要一条检测项目
                if (dgvtesting_ItemsId.Rows.Count == 0)
                {
                    MessageBox.Show("请先新增检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 校验数量输入（检测数量、合格数量）
                if (!int.TryParse(textinspection_Count?.Text, out var inspectionCount) || inspectionCount <= 0)
                {
                    MessageBox.Show("请输入有效的检测数量（>0）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (!int.TryParse(textqualified_Count?.Text, out var qualifiedCount) || qualifiedCount < 0)
                {
                    MessageBox.Show("请输入有效的合格数量（>=0）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (qualifiedCount > inspectionCount)
                {
                    MessageBox.Show("合格数量不能大于检测数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 解析日期
                if (!DateTime.TryParse(datetimeshipment_Date?.text, out var shipmentDate))
                {
                    MessageBox.Show("请填写有效的发货日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (!DateTime.TryParse(datetimeinspection_Date?.text, out var inspectionDate))
                {
                    MessageBox.Show("请填写有效的检验日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 部门
                int departmentId = 0;
                if (cboadddepartment_Id?.SelectedValue != null)
                {
                    int.TryParse(cboadddepartment_Id.SelectedValue.ToString(), out departmentId);
                }

                // 数量
                int noQualifiedCount = int.TryParse(textnoQualified_Count?.Text, out var nqc) ? nqc : Math.Max(0, inspectionCount - qualifiedCount);

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(textinspectionNode?.Text?.Trim()))
                {
                    MessageBox.Show("检验单编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 缺陷率（按已计算结果读取，避免重复计算）
                double fatalRate = double.TryParse(textfatal_Defect_Rate?.Text, out var fr) ? fr : 0;
                double seriousRate = double.TryParse(textserious_Defect_Rate?.Text, out var sr) ? sr : 0;
                double minorRate = double.TryParse(textminor_Defect_Rate?.Text, out var mr) ? mr : 0;

                var items = new List<UpdateGoods_InspectionDtos>();
                foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                {
                    if (row.DataBoundItem is Testing_ItemsDtos item)
                    {
                        int fatal = 0, serious = 0, minor = 0;
                        if (dgvtesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                        {
                            int.TryParse(row.Cells["colFatalCount"].Value.ToString(), out fatal);
                        }
                        if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                        {
                            int.TryParse(row.Cells["colSeriousCount"].Value.ToString(), out serious);
                        }
                        if (dgvtesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                        {
                            int.TryParse(row.Cells["colMinorCount"].Value.ToString(), out minor);
                        }

                        items.Add(new UpdateGoods_InspectionDtos
                        {
                            Id = _inspectionId,
                            Inspection_Type = 2, // 出货检验
                            InspectionNode = textinspectionNode?.Text?.Trim(),
                            InspectionName = textinspectionName?.Text?.Trim(),
                            Shipment_Date = shipmentDate,
                            Inspection_Date = inspectionDate,
                            Department_Id = departmentId,
                            User_Id = 10038,
                            Sale_Id = _selectedSaleId,
                            ProductId = _selectedProductId,
                            Purchase_Id = null,
                            MaterialId = null,
                            Batch = textaddbatch?.Text?.Trim(),
                            Testing_ItemsId = item.Id,
                            Fatal_DefectCount = fatal,
                            Serious_DefectCount = serious,
                            Minor_DefectCount = minor,
                            Inspection_Count = inspectionCount,
                            Qualified_Count = qualifiedCount,
                            NoQualified_Count = noQualifiedCount,
                            Fatal_Defect_Rate = (int)Math.Round(fatalRate),
                            Serious_Defect_Rate = (int)Math.Round(seriousRate),
                            Minor_Defect_Rate = (int)Math.Round(minorRate),
                            Detection_Result = textdetection_Result?.Text?.Trim(),
                            Notes = textnotes?.Text?.Trim()
                        });
                    }
                }

                if (items.Count == 0)
                {
                    MessageBox.Show("请选择至少一条检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 构建请求数据
                var requestData = new { items };

                // 添加调试信息
                Console.WriteLine($"准备发送的数据: {JsonConvert.SerializeObject(requestData, Formatting.Indented)}");
                Console.WriteLine($"检测项目数量: {items.Count}");
                Console.WriteLine($"保存时的销售ID: {_selectedSaleId}, 产品ID: {_selectedProductId}");

                // 使用PutAsync方法发送复杂对象
                var response = await _apiClient.PutAsync<object, TestApiResult<string>>("api/Write/UpdateGoods_Inspection", requestData);

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("检验记录更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 调用刷新回调
                    _refreshCallback?.Invoke();

                    // 关闭窗体
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"更新失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        /// <summary>
        /// 表格单元格值变化事件
        /// </summary>
        private void dgvtesting_ItemsId_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = dgvtesting_ItemsId;
            if (e.ColumnIndex >= 0 && grid.Columns[e.ColumnIndex] != null)
            {
                string columnName = grid.Columns[e.ColumnIndex].Name;
                if (columnName == "colFatalCount" || columnName == "colSeriousCount" || columnName == "colMinorCount")
                {
                    // 重新计算缺陷率
                    CalculateQuantitiesAndRates();
                }
            }
        }

        /// <summary>
        /// 表格操作列点击事件
        /// </summary>
        private void dgvtesting_ItemsId_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = dgvtesting_ItemsId;
            var name = grid.Columns[e.ColumnIndex].Name;

            if (name == "colDelete")
            {
                grid.Rows.RemoveAt(e.RowIndex);
                // 删除检测项目后，清空相关字段
                ClearCalculationResults();
                ClearAllDefectCounts();
                return;
            }

            if (name == "colDefect")
            {
                // 打开缺陷选择窗体，回填数量到当前行
                var currentRowIndex = e.RowIndex;
                var form = new DefectSelectForm((fatal, serious, minor) =>
                {
                    var row = dgvtesting_ItemsId.Rows[currentRowIndex];
                    row.Cells["colFatalCount"].Value = fatal;
                    row.Cells["colSeriousCount"].Value = serious;
                    row.Cells["colMinorCount"].Value = minor;

                    // 触发重新计算
                    CalculateQuantitiesAndRates();
                });
                form.Show(this);
            }
        }

        /// <summary>
        /// 数据绑定完成后处理
        /// </summary>
        private void Dgvtesting_ItemsId_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var grid = dgvtesting_ItemsId;
            grid.AllowUserToAddRows = false;

            // 设置列标题
            if (grid.Columns.Contains("Items_Name")) grid.Columns["Items_Name"].HeaderText = "检测项目";
            if (grid.Columns.Contains("DetectionType_Name")) grid.Columns["DetectionType_Name"].HeaderText = "检验类型";
            if (grid.Columns.Contains("Tools_Name")) grid.Columns["Tools_Name"].HeaderText = "检验工具";

            // 把操作列放到最后
            int count = grid.Columns.Count;
            if (count <= 0) return;
            var orderTail = new List<string> { "colDelete", "colDefect", "colMinorCount", "colSeriousCount", "colFatalCount" };
            int current = count - 1;
            foreach (var name in orderTail)
            {
                if (grid.Columns.Contains(name))
                {
                    grid.Columns[name].DisplayIndex = current;
                    current--;
                }
            }

            // 列重新排序完成后，只清空缺陷数量，保留计算结果
            ClearAllDefectCounts();
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 选择产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnp_Click(object sender, EventArgs e)
        {
            var dialog = new ProductSelectForm(onSelected: prod =>
            {
                if (prod == null) return;
                textproductname.Text = prod.Product_Name ?? string.Empty;
                textproductcode.Text = prod.Product_Number ?? string.Empty;
                textproductunit.Text = prod.Unit ?? string.Empty;
                textproductxh.Text = prod.Specification ?? string.Empty;
                _selectedSaleId = prod.Id;
                _selectedProductId = prod.ProductId;
            });
            dialog.Show(this);
        }
        /// <summary>
        /// 新增检测项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnaddinspe_Click(object sender, EventArgs e)
        {
            var dialog = new GetInspection(onSelected: items =>
            {
                if (items == null || items.Count == 0) return;

                // 确保网格配置完成
                ConfigureTestingItemsGrid();

                if (dgvtesting_ItemsId.DataSource is BindingList<Testing_ItemsDtos> binding)
                {
                    foreach (var it in items)
                    {
                        if (!binding.Any(x => x.Id == it.Id))
                        {
                            binding.Add(it);
                        }
                    }
                }
                else
                {
                    dgvtesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(items);
                }

                // 添加检测项目后，清空相关字段，等待用户输入数量
                ClearCalculationResults();
                ClearAllDefectCounts();
            });

            dialog.Show();
        }
        /// <summary>
        /// 提交（调用保存方法）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddout_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender, e);
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCloseOut_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
